<template>
  <a-modal
    v-model:visible="visible"
    width="800px"
    title-align="start"
    :title="formModel.deptId? '详细': '新增'"
    :top="130"
    :align-center=false
    :mask-closable=false
    :draggable=false
  >
    <a-scrollbar style="max-height:600px; overflow:auto;">
      <a-form
        ref="formModelRef"
        id="addForm"
        label-align="left"
        layout="vertical"
        :label-col-props=labelColProps
        :wrapper-col-props=wrapperColProps
        :model="formModel"
        :rules="rules"
      >
        <a-row justify="space-between">
          <a-col :span="11">
            <a-form-item field="parentId" label="上级部门">
              <a-tree-select
                v-model="formModel.parentId"
                popup-container="#addForm"
                :field-names="fieldNames"
                :data="deptTreeData"
                :disabled="formDisable"
              >
                <template #tree-slot-icon>
                  <icon-folder />
                </template>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="deptName" label="部门名称">
              <a-input
                v-model="formModel.deptName"
                placeholder="请输入部门名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="leader" label="负责人">
              <a-select
                v-model="formModel.leader"
                placeholder="负责人"
                @change="userSelectChange"
              >
                <a-option
                  v-for="item of userSelectData"
                  :key="item.userId"
                  :value="item.userId"
                  :tag-props="{color: 'blue'}"
                >
                  {{ item.userName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="phone" label="负责人电话">
              <a-input v-model="formModel.phone" :disabled="true" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="email" label="负责人邮箱">
              <a-input v-model="formModel.email" :disabled="true" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="orderNum" label="显示排序">
              <a-input-number
                v-model="formModel.orderNum"
                mode="button"
                :default-value="0"
                :min="0"
                :max="999"
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="visible" label="部门状态">
              <a-switch
                v-model="formModel.status"
                type="round"
                :checked-value="'0'"
                :unchecked-value="'1'"
              >
                <template #checked>正常</template>
                <template #unchecked>冻结</template>
              </a-switch>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-scrollbar>
    <template #footer>
      <a-row justify="end">
        <a-button-group>
          <a-button :disabled="loading" @click="cancel">
            取消
          </a-button>
          <a-button
            type="primary"
            :loading="loading"
            :disabled="hasUpdatePermission"
            @click="submit"
          >
            确定
          </a-button>
        </a-button-group>
      </a-row>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineExpose, computed } from 'vue';
import { deptTree, addDept, detailDept, updateDept, SysDept } from '@/api/system/dept';
import { selectUser, SysUser } from '@/api/system/user';
import { rules, permission } from '@/views/system/dept/config';
import { Message, ValidatedError } from '@arco-design/web-vue';
import { labelColProps, wrapperColProps } from '@/components/dialog-add/config';
import useLoading from '@/hooks/loading';
import { hasPermission } from '@/utils/permission';

const emits = defineEmits(['submit']);

const { loading, setLoading } = useLoading(false);

const fieldNames = ref({
  key: 'deptId',
  title: 'deptName',
  children: 'children'
});

const formModelRef = ref();

const visible = ref<boolean>(false);

const formDisable = ref<boolean>(false);

const formModel = ref<SysDept>({});

const deptTreeData = ref([]);

const userSelectData = ref<SysUser[]>([]);

const hasUpdatePermission = computed(() => {
  return formModel.value.deptId && !hasPermission([permission.PERMISSION_UPDATE]);
});

const userSelectChange = (value: any) => {
  value += '';
  userSelectData.value.forEach(item => {
    if (item.userId === value) {
      formModel.value.phone = item.phone;
      formModel.value.email = item.email;
    }
  });
};

const submit = async () => {
  formModelRef.value.validate((errors: undefined | Record<string, ValidatedError>) => {
    if (errors) {
      return;
    }
    setLoading(true);
    if (formModel.value.deptId) {
      updateDept(formModel.value).then(() => {
        submitSuccess();
      }).finally(() => {
        setLoading(false);
      });
      return;
    }
    addDept(formModel.value).then(() => {
      submitSuccess();
    }).finally(() => {
      setLoading(false);
    });
  });
};

const submitSuccess = () => {
  cancel();
  emits('submit');
  Message.success('操作成功');
};

const open = async (record: any, disable: boolean) => {
  const { data } = await deptTree(true);
  deptTreeData.value = data;
  const userResp = await selectUser();
  userSelectData.value = userResp.data;
  if (record && record.deptId) {
    const { data } = await detailDept(record.deptId);
    formModel.value = data;
  } else {
    formModel.value = { parentId: record?.parentId || '0', status: '0', orderNum: 0 };
  }
  visible.value = true;
  formDisable.value = disable;
  formModelRef.value.clearValidate();
  setLoading(false);
};

const cancel = () => {
  visible.value = false;
};

defineExpose({
  open
});
</script>

<script lang="ts">
export default {
  name: 'DeptDialogAdd'
};
</script>

<style scoped>

</style>